package com.jred.jforum.service;

import com.jred.jforum.beans.user.JUser;
import com.jred.jforum.beans.user.Sender;
import com.jred.jforum.beans.user.User;
import com.jred.jforum.beans.user.UserInfo;
import com.jred.jforum.beans.user.UserSettings;
import com.jred.jforum.dao.sqlmap.UserDAO;

public class UserService {

	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public User getUser(String username, String password) {
		User user = new User();
		JUser juser = getJUser(username,password,0);
		if (juser == null) {
			juser = new JUser();
		} else {
			user.setName(juser.getName());
			user.setPassword(juser.getPassword());
			// user.setIp();
			user.setStatus(juser.getStatus());
			user.setIntime(juser.getLast_intime());

			UserInfo info = new UserInfo();
			info.setBirthday(juser.getDob());
			info.setCity(juser.getCity());
			info.setEmail(juser.getEmail());
			info.setHomepage(juser.getHp());
			info.setIcq(juser.getIcq());
			info.setOccupation(juser.getOccupation());
			user.setInfo(info);

			UserSettings settings = new UserSettings();
			settings.setAutologin(juser.getAuto_login() == "1" ? true : false);
			settings.setMes_per_page(juser.getMes_per_page());
			settings.setShow_user_mail(juser.getShow_user_mail() == "1" ? true
					: false);
			settings.setSignature(juser.getSignature());
			user.setSettings(settings);

		}
		return user;
	}
	
	/**
	 * 获取发帖人信息
	 * @param username
	 * @return
	 */
	public Sender getSender(String username) {
		Sender bean = new Sender();
		JUser juser = getJUser(username,"",1);
		
		bean.setIntime(juser.getLast_intime());
        UserInfo info = new UserInfo();
        UserSettings settings = new UserSettings();
        bean.setName(juser.getName());
        info.setCity(juser.getCity());
        settings.setSignature(juser.getSignature());
        bean.setStatus(juser.getStatus());
        bean.setSettings(settings);
        bean.setInfo(info);
		//发帖数
        bean.setTotalMess(userDAO.getMsgCountsByName(juser.getName()).intValue());
		return bean;		
	}
	
	/**
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param grade
	 *            0，验证密码； 1，不验证密码
	 * @return
	 */
	public JUser getJUser(String username, String password, int grade) {
		JUser juser = null;
		switch (grade) {		
		case 0:
			juser = userDAO.getUser(username, password);
			break;
		case 1:
			juser = userDAO.getUserByName(username);
			break;
		}
		return juser;
	}
	


}
